<template>
  <div class="top-nav-body">
    <div class="top-nav">
      <div class="nav-logo">
        <img src="../assets/img/logo_.png" alt="" @click="nav_img">
      </div>
      <div class="top-nav-list">
        <!-- 三级列表 -->
        <Top_nav_top v-if="isTitle"></Top_nav_top>
      </div>
      <div class="nav-input">
        <el-input placeholder="请输入内容" v-model="input" suffix-icon="" @keydown.enter.native="nav_enter" maxlength="10">
        </el-input>
        <div class="nav-input-user" @click="drawer = true" v-show="isUserText">
          个人信息
        </div>
        <!-- 抽屉 -->
        <el-drawer class="drawer" title="个人信息" :visible.sync="drawer" :with-header="false">
          <!-- 用户信息 -->
          <div class="_user">
            <div class="_users">
              <img src="../assets/img/1.png" alt="">
              <div class="_username">
                用户名：{{userinfo.username}}
              </div>
            </div>

            <div class="_user_btn" v-if="!userinfo.username">
              <el-button plain @click="top_nav_btn_login">用户登录</el-button>
              <el-button plain @click="top_nav_btn_new">用户注册</el-button>
            </div>
            <div class="_user_btn" v-if="userinfo.username">
              <el-button plain @click="top_nav_btn_exit">退出登录</el-button>
            </div>
          </div>
          <el-divider></el-divider>
          <!-- 收货地址 -->
          <div class="_address">
            <div class="_address_text">
              收货地址
              <i class="el-icon-receiving"></i>
            </div>
            <div class="_address_content" v-if="!TopNavAddress.length == 0">
              <AddressDescriptions :TopNavAddress="TopNavAddress"></AddressDescriptions>
            </div>
            <div class="_address_add">
              <el-button @click="address_add">添加收货地址</el-button>
              <el-button @click="address_all" v-if="TopNavAddress.length > 1">查看更多地址</el-button>
            </div>
          </div>
          <el-divider></el-divider>
        </el-drawer>
      </div>
      <div class="themeSwitch">
        <Top_Button></Top_Button>
      </div>
    </div>

    <!-- 添加收货地址 -->
    <el-dialog title="收货地址" :visible.sync="dialogFormVisible" width="40%" :center="true">
      <el-form :model="addressObj" :rules="rules" ref="addressObj">
        <el-form-item label="收货人" :label-width="formLabelWidth" prop="receiverName">
          <el-input v-model.number="addressObj.receiverName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="receiverMobile">
          <el-input v-model.number="addressObj.receiverMobile" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所在地址" :label-width="formLabelWidth">
          <el-cascader size="medium" :options="options" v-model="selectedOptions" @change="handleChange" class="asd"></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" :label-width="formLabelWidth" prop="addr">
          <el-input type="textarea" v-model="addressObj.addr"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="address_post">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 查看更多地址 -->
    <el-dialog title="我的收货地址" :visible.sync="dialogTableVisible">
      <el-table :data="TopNavAddress" border style="width: 100%">
        <el-table-column fixed prop="receiverName" label="姓名" width="120" align="center" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="receiverMobile" label="手机号" width="120" align="center" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="province" label="省份" width="120" align="center" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="city" label="市区" width="120" align="center" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="area" label="地址" width="120" align="center" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="addr" label="详细地址" width="300" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button>
            <el-button type="text" size="small">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

  </div>

</template>

<script>
// 导入三级数据
import { codeToText, regionData } from 'element-china-area-data'
import Top_Button from '../components/Top-button'
import Top_nav_top from '../components/Top-nav-top'
import AddressDescriptions from '../components/AddressDescriptions'
import { getUserName, getUserAddress } from '../config/api'

export default {
  name: 'top-nav',
  props: {
    enter: Function,
    // 控制top显示隐藏
    isTitle: {
      type: Boolean,
      default: true
    },
    // 控制显示个人信息
    isUserText: {
      type: Boolean,
      default: true
    }
  },
  components: {
    Top_Button,
    Top_nav_top,
    AddressDescriptions
  },
  data() {
    return {
      size: '',
      // 输入框
      input: '',
      // 抽屉卡关
      drawer: false,
      // 用户信息
      userinfo: {},
      token: this.$token(),
      // 收货地址数据
      TopNavAddress: [],
      // 收货地址弹出框状态
      dialogFormVisible: false,
      // 校验规则
      rules: {
        receiverName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        receiverMobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          // { type: 'number', message: '手机号必须为数字值', trigger: 'blur' },
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        addr: [{ required: true, message: '请填写活动形式', trigger: 'blur' }]
      },
      // 表单的item宽度
      formLabelWidth: '100px',
      // 三级区域选择
      options: regionData,
      selectedOptions: [],
      loc: [], // 地址
      // 添加收货地址对象参数
      addressObj: {
        userId: window.localStorage.getItem('userId'), // 用户id
        receiverName: '', // 收件人name
        receiverMobile: '', // 收件人手机号
        province: '', // 省份
        city: '', // 城市
        area: '', // 区县
        addr: '', // 详细地址
        postCode: '001100' // 邮编
      },
      // 查看更多地址
      dialogTableVisible: false
    }
  },
  computed: {},
  methods: {
    // 点击logo跳转到home
    nav_img() {
      if (this.$route.fullPath == '/home') return
      this.$router.push({
        path: '/home'
      })
    },
    nav_enter() {
      // console.log(this.input)
      this.enter(this.input)
      this.input = ''
    },

    // 登录
    top_nav_btn_login() {
      this.$router.push({
        path: '/login',
        query: {
          top_nav: true
        }
      })
    },
    // 新建
    top_nav_btn_new() {},
    // 退出登录
    top_nav_btn_exit() {
      window.localStorage.removeItem('shopping_token')
      window.localStorage.removeItem('userId')
      this.userinfo = {}
    },
    // 更改收货地址弹出框状态
    isAddressDialog(value) {
      this.dialogFormVisible = value
    },
    // 三级区域选择变化
    handleChange(value) {
      for (let i = 0; i < this.selectedOptions.length; i++) {
        this.loc[i] = codeToText[this.selectedOptions[i]]
      }
      // 添加到请求对象中
      this.addressObj.province = this.loc[0] // 省
      this.addressObj.city = this.loc[1] // 市
      this.addressObj.area = this.loc[2] // 县
    },
    // 确定 发起请求
    address_post() {
      this.$isExistUser()
      if (!this.addressObj.receiverName) return this.$message.error('请填写姓名')
      if (!this.addressObj.receiverMobile) return this.$message.error('请填写手机号')
      if (!this.loc[0]) return this.$message.error('请选择区域')

      // this.addressObj.userId = window.localStorage.getItem('userId') // 用户id

      postAddress(this.token, this.addressObj)
        .then(result => {
          if (result.status == 200) {
            if (result.data.code == 200) {
              this.dialogFormVisible = false
              this.getAddress()

              this.$message({
                showClose: true,
                message: '添加成功',
                type: 'success'
              })
            }
          }
        })
        .catch(err => {
          // console.log(err)
          this.$message.error('添加失败')
        })
    },
    // 添加收货地址
    address_add() {
      this.isAddressDialog(true)
    },
    // 查看更多
    address_all() {
      // 显示
      this.dialogTableVisible = true
    },
    handleClick(row) {
      console.log(row)
    }
  },
  mounted() {
    // 请求用户信息
    // this.Base64.decode(window.localStorage.getItem('shopping_token')) 解密
    getUserName(this.token)
      .then(result => {
        if (result.status === 200) {
          this.userinfo = result.data.data.userInfo
          // 查询收货地址
          getUserAddress(this.token, this.userinfo.userId)
            .then(result => {
              if (result.status == 200) {
                if (result.data.code == 200) {
                  this.TopNavAddress = result.data.data

                  // console.log(this.TopNavAddress)
                }
                if (result.data.code == 404) {
                  this.$message.error('登录过期，请重新登录')
                  this.top_nav_btn_exit()
                  this.top_nav_btn_login()
                }
              }
            })
            .catch(err => {
              console.log(err)
            })
        }
      })
      .catch(err => {
        console.log(err)
        try {
          if (err.response.status === 500) {
            this.$message({
              showClose: true,
              message: '登录信息过期，请重新登录',
              type: 'error'
            })
            window.localStorage.removeItem('shopping_token')
            this.$router.push({
              path: '/login',
              query: {
                top_nav: true
              }
            })
          }
        } catch (error) {
          // alert('服务器崩了')
          console.log('服务器蹦了')
        }
      })
  }
}
</script>

<style lang="less" scoped>
.top-nav-body {
  position: relative;
  background-color: @nav_back;
  color: @nav_color;

  .top-nav {
    width: 100%;
    height: @nav_size_60px;
    display: flex;
    justify-content: flex-start;

    .nav-logo {
      flex: 0.5;
      height: @nav_size_60px;
      line-height: @nav_size_60px;
      margin-left: @login_size_10px + 40;
      img {
        height: 60px;
        display: inline-block;
      }
    }
    // 三级列表
    .top-nav-list {
      display: flex;
      justify-content: center;
      align-items: center;
      flex: 1.5;
    }
    // 搜索框
    .nav-input {
      line-height: 60px;
      flex: 0.8;
      display: flex;

      // 点击展示抽屉
      .nav-input-user {
        margin-left: @login_size_10px;
        font-size: 18;
        cursor: pointer;
      }
      // 抽屉
      .drawer {
        /deep/.el-drawer.rtl {
          background-color: @html_back;
        }
        .el-drawer {
          .el-drawer__body {
            // 用户信息
            ._user {
              display: flex;
              height: 100px;
              justify-content: space-between;

              ._users {
                display: flex;
                img {
                  width: 80px;
                  height: 80px;
                  display: block;
                  margin: 10px;
                }
              }
              ._user_btn {
                margin-right: 20px;
                display: flex;
                flex-direction: column;
                justify-content: space-evenly;
                .el-button + .el-button {
                  margin-left: 0px;
                }
              }
            }
            // 收货地址
            ._address {
              margin: 10px;
              line-height: 35px;
              ._address_text {
                text-align: center;
                font-size: 22px;
              }
              ._address_content {
              }
              ._address_add {
                margin-top: 20px;
                text-align: center;
              }
            }
          }
        }
      }
      .el-input {
        flex: 2;
        // input 输入框
        .el-input__inner {
          background-color: @nav_back;
        }
      }

      .el-dropdown {
        flex: 0.8;
        text-align: center;

        .el-dropdown-link,
        el-dropdown-selfdefine {
          color: @nav_color;
        }
      }
      .el-dropdown-link {
        cursor: pointer;
        color: #555353;
      }
      .el-icon-arrow-down {
        font-size: 12px;
      }
    }
    .themeSwitch {
      display: flex;
      margin: 0 10px;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>